#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>

#define RL 4
#define LL 5

const char* ssid = "sync_ap";
const char* password = "zxcv123456";

WiFiServer server(1234);
bool clientConnected = false;
bool syncCompleted = false;
unsigned long startTime = 0;
const unsigned long syncTimeout = 70000;  // 64秒同步超时
int StartDelay = 64000;                   // 1秒后自动启动

void clockTurn() {
  digitalWrite(RL, HIGH);  // RL下管关闭
  digitalWrite(LL, LOW);   // LL下管开启
}

void unclockTurn() {
  digitalWrite(RL, LOW);   // RL下管开启
  digitalWrite(LL, HIGH);  // LL下管关闭
}

void stopAll() {
  digitalWrite(RL, HIGH);
  digitalWrite(LL, HIGH);
}


void setup() {
  Serial.begin(115200);
  delay(1000);


  Serial.println("ESP32-S3引脚初始化完成");
  // 设置AP模式
  WiFi.softAP(ssid, password);
  // 启动TCP服务器
  server.begin();
  Serial.println("TCP server started");
  startTime = millis();
  Serial.println("ok");
  unclockTurn();
}



void loop() {
  if ((millis() - startTime) % 1000 == 0) Serial.println((millis() - startTime) / 1000);
  // 检查同步超时
  if (!syncCompleted && millis() - startTime > syncTimeout) {
    Serial.println("Sync timeout, waiting for auto start...");
    syncCompleted = true;  // 防止重复进入
    startProgram();
  }


  // 检查客户端连接
  WiFiClient client = server.available();
  if (client) {
    Serial.println("New client connected");
    clientConnected = true;

    // 等待客户端发送同步请求
    unsigned long connectionTime = millis();
    while (client.connected() && millis() - startTime < syncTimeout) {
      if (client.available()) {
        String request = client.readStringUntil('\n');
        request.trim();

        if (request == "SYNC_REQUEST") {
          Serial.println("Sync request received");
          wait(64000 - millis());
          client.println("SYNC_ACK");
          syncCompleted = true;
          Serial.println("Sync completed, starting program...");
          startProgram();
          break;
        }
      }
      delay(10);
    }

    client.stop();
    Serial.println("Client disconnected");
  }
}

void wait(int t) {
  for (int i = 0; i < t + 1; i++) {
    if (i % 1000 == 0) Serial.println(t - i);
    delay(1);
  }
}


void startProgram() {
  Serial.print(millis());
  Serial.println("Program started on AP device!");

  while (true) {
    clockTurn();
    Serial.println("升");
    wait(64000);

    // 逆时针旋转
    unclockTurn();
    Serial.println("降");
    wait(64000);
  }
}